package com.server.libs.EmailCode;

import com.server.dao.MobileAppDao;
import com.server.pojo.MobileApp;
import com.server.libs.ret.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class BindEmailCode {
    @Autowired
    StringRedisTemplate redis;

    @Autowired
    MobileAppDao mobileAppDao;

    final private String suffix = "_email_code_bind";

    public String create(String email,MobileApp mobileApp){
        if (!email.matches("^([a-zA-Z]|[0-9])(\\w|\\-)+@[a-zA-Z0-9]+\\.([a-zA-Z]{2,4})$")) {
            throw  new RE("请输入正确邮箱！");
        }

        if(mobileAppDao.findByEmail(email)!=null) throw new RE("该邮箱已被绑定");

        if (isSend(email,mobileApp)){
            throw  new RE("请不要频繁获取验证码！");
        }

        email += suffix + mobileApp.getAccount();
        String code = String.format("%06d",(int)(Math.random()* (999999)+1));//产生(0,999999]之间的随机数
        redis.opsForValue().set(email,code,600, TimeUnit.SECONDS);
        return code;
    }

    public void check(String email,String code,MobileApp mobileApp){
        if(mobileAppDao.findByEmail(email)!=null) throw new RE("该邮箱已被绑定");

        email += suffix + mobileApp.getAccount();
        if(!code.equalsIgnoreCase(redis.opsForValue().get(email))){
            throw new RE("验证码不正确！");
        }
        redis.delete(email);
    }

    public boolean isSend(String email,MobileApp mobileApp){
        return (getExpire(email,mobileApp) >= 600-60);
    }

    public void del(String email,MobileApp mobileApp){
        email += suffix + mobileApp.getAccount();
        redis.delete(email);
    }

    public Long getExpire(String email,MobileApp mobileApp){
        email += suffix + mobileApp.getAccount();
        Long expireTime = redis.getExpire(email, TimeUnit.SECONDS);
        if (expireTime == null) expireTime = -1L;
        return expireTime;
    }
}
